﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Amazon;
using Amazon.S3;
using DevToolBox.Cloud.Common;
using Amazon.S3.Model;

namespace DevToolBox.Cloud.Amazon
{    

    public class AmazonS3Operations : IManageable
    {
        private string tenantBucketNamePrefix = "BUCKET_FOR_TENANTID_";
        private AmazonS3Config config = null;
        private AmazonS3 client;

        public AmazonS3Operations()
        {
            config = new AmazonS3Config();
            config.UseSecureStringForAwsSecretKey = false;
            client = AWSClientFactory.CreateAmazonS3Client(config);
        }

        public void Create(object configObject)
        {
            string tenantId = Convert.ToString(configObject);
            string tenantBucketName = tenantBucketNamePrefix + tenantId;
            PutBucketRequest request = new PutBucketRequest();
            request.BucketName = tenantBucketName;
            var createRes = client.PutBucket(request);

            var versionConfig = new S3BucketVersioningConfig();
            versionConfig.EnableMfaDelete = false;
            versionConfig.Status = "Enabled";

            var versionReq = new SetBucketVersioningRequest();
            versionReq.BucketName = tenantBucketName;
            versionReq.VersioningConfig = versionConfig;
            var verRes = client.SetBucketVersioning(versionReq);
        }

        public string GetStatus(string key)
        {
            var response = client.ListBuckets();
            string tenantBucketName = tenantBucketNamePrefix + key;

            foreach (S3Bucket b in response.Buckets)
            {
                if (tenantBucketName == b.BucketName)
                {
                    return b.CreationDate;
                }
            }

            return null;
        }

        public void Dispose()
        {
            if (client != null)
            {
                client.Dispose();
            }
        }

        public void Delete(string key)
        {
            DeleteBucketRequest request = new DeleteBucketRequest();
            string tenantBucketName = tenantBucketNamePrefix + key;
            request.BucketName = tenantBucketName;
            client.DeleteBucket(request);
        }

        public void Update(object configObject)
        {
            //This operation is not needed yet
            throw new NotImplementedException();
        }
    }
}
